package com.controller;

import java.io.Serializable;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class RabbitController {

	private static final String Prefix = "rabbit";

	@Autowired
	private Environment env;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
	private ObjectMapper objectMapper;

	/**
	 * 发送简单消息
	 * 
	 * @param message
	 * @return
	 */
	@GetMapping(Prefix + "/simple/message/send")
	public String sendSimpleMessage(@RequestParam String message) {
		try {
			log.info("待发送的消息： {} ", message);

			rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
			rabbitTemplate.setExchange(env.getProperty("basic.info.mq.exchange.name"));
			rabbitTemplate.setRoutingKey(env.getProperty("basic.info.mq.routing.key.name"));

			Message msg = MessageBuilder.withBody(objectMapper.writeValueAsBytes(message)).build();
			rabbitTemplate.convertAndSend(msg);
		} catch (Exception e) {
			log.error("发送简单消息发生异常： ", e.fillInStackTrace());
		}
		return "发送成功";
	}

	/**
	 * 发送对象消息
	 * 
	 * @param user
	 * @return
	 */
	@PostMapping(value = Prefix + "/object/message/send", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public String sendObjectMessage(@RequestBody User user) {
		try {
			log.info("待发送的消息： {} ", user);

			rabbitTemplate.setExchange(env.getProperty("basic.info.mq.exchange.name"));
			rabbitTemplate.setRoutingKey(env.getProperty("basic.info.mq.routing.key.name"));
			rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());

			Message msg = MessageBuilder.withBody(objectMapper.writeValueAsBytes(user))
					.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT).build();
			rabbitTemplate.convertAndSend(msg);
		} catch (Exception e) {
			log.error("发送对象消息发生异常： ", e.fillInStackTrace());
		}
		return "发送成功";
	}

	@Data
	public static class User implements Serializable {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private String userName;
		private String passWord;
	}

}
